package com.module.launcher.view

import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import com.module.ad_gromore.SplashAdListener
import com.module.ad_gromore.ad.SplashAd
import com.module.app.base.BaseActivity
import com.module.app.pop.ProgressPop
import com.module.app.utils.InitializationUtils
import com.module.app.utils.UpdateUtils
import com.module.base.cache.CacheSDK
import com.module.base.ext.countDownByFlow
import com.module.base.utils.LogUtils
import com.module.base.utils.ToastUtils
import com.module.frame.app.AppManager
import com.module.frame.app.AppStatusManager
import com.module.frame.ext.observe
import com.module.launcher.R
import com.module.launcher.databinding.LauncherActivityWelcomeBinding
import com.module.launcher.dialog.AgreeDialog
import com.module.launcher.model.WelcomeViewModel
import com.module.launcher.utils.startMain

class WelcomeActivity : BaseActivity<WelcomeViewModel, LauncherActivityWelcomeBinding>() {

    private var isForceUpdate = false
    private var progressPop: ProgressPop? = null
    private var agreeDialog: AgreeDialog? = null

    /**
     * 试图绑定ViewModel
     */
    override fun bingViewModel() {
        //绑定vm
        mDatabind.vm = mViewModel
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        AppStatusManager.getInstance().appStatus = AppStatusManager.AppStatusConstant.APP_NORMAL
        super.onCreate(savedInstanceState)
    }

    override fun onResume() {
        super.onResume();
        if (isForceUpdate && progressPop?.isShow == true) {
            //防止强制更新后，没有更新，又返回回来，弹窗没了
            setUpDate();
        }
    }

    override fun initView() {

        //启动异常处理
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            if (AppManager.getActivity(MainActivity::class.java) != null) {
                finish()
                startMain()
                CacheSDK.put(com.module.app.bean.IType.ITemporaryCache.FLAG_ACTIVITY_BROUGHT_TO_FRONT, true)
            } else {
                finish()
            }
            return
        }
        super.initView()
        //标题配置
        mDatabind.tvTitle?.apply {
            //设置粗细
            paint.style = Paint.Style.FILL_AND_STROKE
            paint.strokeWidth = 0.6f
        }
        //内容配置
        mDatabind.tvContent.apply {
            //设置粗细
            paint.style = Paint.Style.FILL_AND_STROKE
            paint.strokeWidth = 0.1f
            text = com.module.app.bean.ConfigBean.getInstance().welcomeSlogan
        }

    }

    override fun initListener() {
        super.initListener()
        observe(mViewModel.configFlow) {
            if (it) {
                next()
            }
        }
        observe(mViewModel.updateFlow) {
            if (it) {
                setUpDate()
            }
        }
    }

    override fun initData() {
        //防止启动异常
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            return
        }
        super.initData()
        val isAgreement = CacheSDK.get(
            com.module.app.bean.IType.ICache.AGREEMENT,
            Boolean::class.java
        )
        if (!isAgreement) {
            agreeDialog = AgreeDialog(getContext()) { v ->
                val i = v.id
                when (i) {
                    R.id.btn_agree -> {
                        onAgreeDialog()
                    }
                    R.id.btn_no_agree -> {
                        onNoAgreeDialog()
                    }
                    R.id.tv_law -> {
                        com.module.app.web.WebViewActivity.startService(getContext())
                    }
                    R.id.tv_private -> {
                        com.module.app.web.WebViewActivity.startPrivacy(getContext())
                    }
                }
            }
            agreeDialog?.setCancelable(false)
            agreeDialog?.setCanceledOnTouchOutside(false)
            if (agreeDialog != null) {
                agreeDialog?.show()
            }
        } else {
            onAgreeDialog()
        }
    }

    /**
     * 同意协议。
     */
    private fun onAgreeDialog() {
        if (agreeDialog != null) {
            agreeDialog!!.dismiss()
        }
        init()
    }

    private fun onNoAgreeDialog() {
        ToastUtils.showShort(R.string.launcher_must_agree)
        finish()
    }

    /**
     * 初始化
     */
    private fun init() {
        com.module.app.utils.MyInitializationUtils.initSDK()
        InitializationUtils.initData()
        CacheSDK.put(com.module.app.bean.IType.ICache.AGREEMENT, true)

        //请求配置
        mViewModel.getConfig()
    }

    fun next() {
        if (com.module.app.utils.UserUtils.isVip()) {
            jump()
            return
        }
        when (com.module.app.bean.ConfigBean.getInstance().ad.adType) {
            com.module.app.bean.IType.IAdType.TX -> loadGroMoreAd()
            com.module.app.bean.IType.IAdType.TT -> loadGroMoreAd()
            else -> {
                LogUtils.e("不启动开屏广告")
                //倒计时3s.进入
                countDownByFlow(3,
                    {
                        LogUtils.d("启动倒计时:$it s")
                    }, {
                        LogUtils.d("倒计时结束")
                        jump()
                    })
            }
        }
    }

    private fun jump() {
        if (isForceUpdate) {
            return
        }
        goMainActivity()
    }

    private fun goMainActivity() {
        startMain()
        finish()
        overridePendingTransition(
            R.anim.activity_enter_anim,
            R.anim.activity_exit_anim
        )
    }

    /**
     * 启动GroMore广告
     */
    private fun loadGroMoreAd() {
        val groMore = com.module.app.bean.ConfigBean.getInstance().adGroMore
        if (groMore == null) {
            jump()
            return
        }
        //启动广告
        SplashAd.loadAd(
            this,
            groMore.appId,
            groMore.splashId,
            groMore.splashDoudiId,
            object : SplashAdListener {
                override fun getAdView(): ViewGroup {
                    return mDatabind.layoutAd
                }

                override fun isFinishing(): Boolean {
                    return getActivity().isFinishing
                }

                override fun goActivity() {
                    jump()
                }
            })
    }

    private fun setUpDate() {
        isForceUpdate = com.module.app.bean.ConfigBean.getInstance().isForceUpdate
        if (isForceUpdate) {
            //弹窗更新
            progressPop = ProgressPop.Builder(getContext())
                .setContentGravity(Gravity.LEFT)
                .setTitle(R.string.update_title)
                .setContent(com.module.app.bean.ConfigBean.getInstance().appVersionContent)
                .setAutoDismiss(false)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setConfirmButton(R.string.right_off_update)
                .setCancelButton(R.string.finish_app)
                .setOnCancelListener {
                    progressPop?.dismiss()
                    getActivity().finish()
                }
                .setOnConfirmListener {
                    UpdateUtils.update(
                        getContext(),
                        com.module.app.bean.ConfigBean.getInstance().downloadApk,
                        com.module.app.bean.ConfigBean.getInstance().appVersionName
                    )
                }
                .create()
            progressPop?.show()
        }
    }
}